<template>
    <div class="main_recommend">
        <div class="main_recommend_body">
            <a-spin :spinning="spinning" :tip="'加载中'" :delay="100">
                <div v-for="(item,index) in list" :key="item.id">
                    <div>
                        <router-link :to="{
                        path: '/problemDetails',
                        query: {
                        id:item.id
                      }
                    }">
                            <div class="main_recommend_body_title">
                                <strong v-html="item.title"></strong>
                            </div>
                            <!--              <div class="main_recommend_body_title_hover"  v-dompurify-html="item.title">-->
                            <!--                <strong v-html="item.title"></strong>-->
                            <!--              </div>-->
                        </router-link>
                    </div>
                    <div class="main_recommend_body_second">
                        <div>{{ item.nickname }}</div>
                        <div class="main_recommend_body_createTime">发布于：{{ item.createTime }}</div>
                    </div>
                    <div class="main_recommend_body_statistical">
                        <img @click="userGiveALikeProblem(item,index)" v-if="item.isLike===1"
                             src="../../../../assets/img/answer/点赞.png"
                             class="main_recommend_body_statistical_like" alt="点赞"/>
                        <img @click="userGiveALikeProblem(item,index)" v-else
                             src="../../../../assets/img/answer/未点赞.png"
                             class="main_recommend_body_statistical_like" alt="未点赞"/>
                        &nbsp;点赞：{{ item.likeCount }}
                        <div class="main_recommend_body_statistical_browse">浏览：{{ item.views }}</div>
                        <div class="main_recommend_body_statistical_comment">评论：{{ item.reply }}</div>
                    </div>
                </div>
                <a-pagination v-model:current="pagination.current"
                              v-model:page-size="pagination.pageSize"
                              :size="pagination.size"
                              :total="pagination.total"
                              :show-total="pagination.showTotal"
                              :show-size-changer="pagination.showSizeChanger"
                              :page-size-options="pagination.pageSizeOptions"
                              @showSizeChange="pagination.onShowSizeChange"
                              @change="pagination.onChange"
                              style="text-align: center;margin: 10px;"
                />
            </a-spin>
        </div>
    </div>
</template>

<script setup lang="ts">
import {getList, like, getUserGiveALikeListById, searchProblem} from "@/api/home/answer";
import {onMounted, reactive, ref} from "vue";
import {Answer, GiveALike, RequestParams} from "@/model/home/answer";
// @ts-ignore
import cookie from 'js-cookie'
// @ts-ignore
import Publish from 'pubsub-js'
import {checkUserLogin} from "@/utils/getUser";
import {saveScrollLocation} from "@/utils/storageScrollLocation"
import router from "@/router";
import lodash from "lodash";
import {message} from "ant-design-vue";

//是否显示加载中
const spinning = ref<boolean>(true);

//所有问题列表
const list = ref<Answer[]>([])

//全文检索所需的参数
const requestParams = ref<RequestParams>({
    key: '',
    page: 1,
    size: 10,
    sortBy: ''
})

//获取所有问题
const handleList = async () => {
    requestParams.value.sortBy = "id"
    const res = await searchProblem(requestParams.value)
    res.data.data.pageResult.problems.map((item: Answer) => {
        item.title = item.title.replaceAll("<em>", "<nobr style='color: red;white-space: nowrap;'>")
        item.title = item.title.replaceAll("</em>", "</nobr>")
    })
    list.value = res.data.data.pageResult.problems
    pagination.value.total = res.data.data.pageResult.total
    await userGiveALike()
}

//分页
const pagination = ref({
    size: 'large',
    current: 1,
    pageSize: 10,
    total: 0,
    pageSizeOptions: ['10', '20', '30'],
    showTotal: (total: number) => {
        return " 共" + total + "条"
    },
    showSizeChanger: true,
    onShowSizeChange: (current: number, pageSize: number) => {
        pagination.value.pageSize = pageSize
        requestParams.value.size = pageSize
        handleList()
        spinning.value = true
        setTimeout(async () => {
            //判断当前用户是否点赞
            await userGiveALike()
            spinning.value = false
        }, 1000)
    },
    onChange: (current: number) => {
        pagination.value.current = current
        requestParams.value.page = current
        handleList()
        spinning.value = true
        setTimeout(async () => {
            //判断当前用户是否点赞
            await userGiveALike()
            spinning.value = false
        }, 1000)
    }
})

//接收全文检索的数据
const receiveSearchProblemList = () => {
    Publish.unsubscribe('searchProblemList')
    Publish.subscribe('searchProblemList', (functionName: string, message: any, c: any) => {
        list.value = message[0]
        requestParams.value.key = message[1]
        pagination.value.total = message[2]
        router.push('/answer/recommend')
        userGiveALike()
    })
}

//接收子组件的回调  重新获取所有问题
const receiveChile = () => {
    Publish.unsubscribe('handleList')
    Publish.subscribe('handleList', () => {
        handleList()
    })
}

//用户点赞问题需要的参数
const giveALike = ref<GiveALike>({
    userId: 0,
    problemId: 0
})

//当前用户已点赞的数据
const userGiveALikeList = ref()

//判断当前用户是否点赞
const userIsGiveALikeProblem = () => {
    for (let i = 0; i < list.value.length; i++) {
        for (let j = 0; j < userGiveALikeList.value.length; j++) {
            if (list.value[i].id === userGiveALikeList.value[j].problemId) {
                list.value[i].isLike = userGiveALikeList.value[j].isLike
                break;
            } else {
                list.value[i].isLike = 0
            }
        }
    }
    //保存页面滚动条位置
    saveScrollLocation()
}

//从关联表获取当前用户点赞的数据
const userGiveALike = async () => {
    const res = await getUserGiveALikeListById(userId)
    userGiveALikeList.value = res.data.data.list
    setTimeout(async () => {
        //判断当前用户是否点赞
        await userIsGiveALikeProblem()
        spinning.value = false
    }, 1000)
}

//用户点赞问题
const userGiveALikeProblem = async (row: any, index: number) => {
    giveALike.value.userId = userId
    giveALike.value.problemId = row.id
    if (!await checkUserLogin()) {
        message.warn('未登录，无法点赞')
    } else {
        like(giveALike.value).then((res) => {
            list.value[index].isLike = list.value[index].isLike === 1 ? 0 : 1;
            //如果点赞，则点赞人数+1
            if (res.data.data.isLike === 1) {
                message.success('点赞成功')
                list.value[index].likeCount = list.value[index].likeCount + 1
            } else {
                message.error('已取消点赞')
                list.value[index].likeCount = list.value[index].likeCount - 1
            }
        })
    }
}

let userId = 0

//当前登录用户的id
const getUserId = () => {
    if (cookie.get('userinfo') != null) {
        userId = JSON.parse(cookie.get('userinfo')).id
        if (userId == 0) {
        } else {
            setTimeout(() => {
                userGiveALike()
            }, 100)
        }
    } else {
        userId = 0
    }
}

getUserId()
handleList()
onMounted(() => {
    receiveChile()
    receiveSearchProblemList()
})
</script>

<style lang="less" scoped>
.main_recommend {
  padding-left: 5px;

  .main_recommend_body {
    margin-top: 10px;

    .main_recommend_body_title {
      font-size: 20px;
      padding: 5px 5px 5px 0;
      cursor: pointer;
      width: 90%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .main_recommend_body_title:hover {
      color: red;
    }

    .main_recommend_body_second {
      display: flex;
      margin-top: 10px;

      .main_recommend_body_createTime {
        margin-left: auto;
        margin-right: 50px;
      }
    }

    .main_recommend_body_statistical {
      display: flex;
      margin-top: 10px;
      padding-bottom: 2px;
      border-bottom: 1px solid #f0f0f0;
      margin-right: 5px;

      .main_recommend_body_statistical_like {
        width: 20px;
        height: 20px;
        cursor: pointer;
      }

      .main_recommend_body_statistical_browse {
        margin-left: 50px;
        margin-right: 10px;
      }

      .main_recommend_body_statistical_comment {
        margin-left: 50px;
        margin-right: 10px;
      }
    }
  }
}
</style>